from django.contrib.auth.models import User
from django.db import models

from api_case.models import Case as APICase
from project.models import Project
from ui_case.models import Case as UICase

# pool = ThreadPoolExecutor(max_workers=6)


# Create your models here.
class Suite(models.Model):
    objects: models.QuerySet
    name = models.CharField("套件名称", max_length=32)
    project = models.ForeignKey(
        Project, on_delete=models.CASCADE, related_name="suite_project"
    )
    description = models.CharField(
        "套件详细描述", max_length=512, blank=True, default=""
    )
    user = models.ForeignKey(User, on_delete=models.SET_DEFAULT, default=1)
    execute_type = models.CharField(
        choices=[(1, "执行一次"), (2, "定时执行"), (3, "webhook执行")], default=1
    )

    api_case_list = models.ManyToManyField(APICase, blank=True)
    ui_case_list = models.ManyToManyField(UICase, blank=True)

    # 套件中接口测试用例数量
    def get_api_case_count(self):
        count = self.api_case_list.all().count()
        return count

    # 套件中UI测试用例数量
    def get_ui_case_count(self):
        count = self.api_case_list.all().count()
        return count


# 保存用例执行结果的数据表
class RunResult(models.Model):
    """套件运行结果"""

    objects: models.QuerySet

    class RunStatus(models.IntegerChoices):
        Init = 0, "初始化"
        Ready = 1, "准备开始"
        Running = 2, "正在执行"
        Reporting = 3, "正在生成报告"
        Done = 4, "执行完成"
        Error = -1, "执行出错"
        ReportError = -2, "报告生成失败"

    class IsPass(models.IntegerChoices):
        no_execute = 0, "未执行"
        passed = 1, "通过"
        failed = 2, "失败"

    suite = models.ForeignKey(Suite, on_delete=models.CASCADE)
    project = models.ForeignKey(
        Project, on_delete=models.CASCADE, related_name="run_result_project"
    )

    path = models.CharField("用例路径", max_length=255)
    is_pass = models.IntegerField(
        "是否通过", choices=IsPass.choices, default=IsPass.no_execute
    )
    status = models.IntegerField(
        "执行状态", choices=RunStatus.choices, default=RunStatus.Init
    )

    create_datetime = models.DateTimeField("创建时间", auto_now_add=True)
    update_datetime = models.DateTimeField("更新时间", auto_now=True)
